import { getSvgHtml } from '../../svgHtml'
import { changeNumberToWanYi, clearUrlHttp, drawCardToBase64, DrawCardToBase64Option, handleImageUrlToWebp, replaceHtmlToSafeStr } from '../../utils'
import Card, { CardValue, LOAD_STATUS } from '../card'

export interface LiveCardInfo {
    area_v2_name: string,
    cover: string,
    face: string,
    live_status: number,
    online: number,
    pendent_ru: string,
    pendent_ru_color: string,
    pendent_ru_pic: string,
    role: number,
    room_id: number,
    title: string,
    uid: number,
    uname: string,
}

export type LiveCardCreateValue = CardValue<LiveCardInfo>
export default class LiveCard extends Card {
    static blotName = 'live-card'
    static className = 'live-card'

    static create(value: LiveCardCreateValue) {
        // 根据id获取商品信息，将商品新增转为图片，最终插入图片，并将id作为data-id，存入的参数中
        const node: HTMLElement = super.create(value)
        if (value !== null && value?.status === LOAD_STATUS.LOADED) return node
        node.setAttribute('contenteditable', 'false')
        if (!value.src && !value.id) return node
        node.classList.add('card')
        const type = this.verify(value)
        return type === 'render' ? (this.renderHandle(value, node), node) :
            type === 'draw' ? (this.drawHandle(value, node), node) :
                node
    }

    static renderHandle(value: LiveCardCreateValue, node: HTMLElement) {
        // return node
        value.id && this.renderCard(value).then((dom: HTMLElement) => { node.appendChild(dom) })
    }
    static drawHandle(value: LiveCardCreateValue, node: HTMLElement) {
        // return node
        const { id } = value
        if (id) {
            const loadingImage = this.createLoadingImage()
            node.appendChild(loadingImage)
            return this.drawCard(id, value).then((res) => {
                value.src = res
                value?.uploadHandle?.(loadingImage, value) || this.uploadHandle?.(loadingImage, value)
                return null
            })
        }
    }
    static renderCard(value: LiveCardCreateValue) {
        const { id, info } = value
        return id && info ? createLiveCardDom(info).then((res) => {
            return res.dom
        }) : getLiveDetail(id).then((res) => {
            return createLiveCardDom(res[id]).then((res) => {
                return res.dom
            })
        })
    }
    static drawCard(id: string, value: LiveCardCreateValue) {
        const render = async (v: LiveCardCreateValue['info']) => {
            const res = await createLiveCardDom(v, { draw: true, wrap: document.querySelector(this.drawWrap) as HTMLElement })
            return res.base64!
        }
        return value.info ? render(value.info) : getLiveDetail(id).then(res => {
            return render(res[id])
        })
    }
}

export const createLiveCardDom = (
    info: LiveCardCreateValue['info'],
    option?: DrawCardToBase64Option
) => {
    const { room_id, area_v2_name, cover, online, live_status, uname, title } = info || {}
    const r = option || {}
    const living = live_status === 1
    let o = ''
    if (info?.room_id) {
        o = `
            <a class="live-card-holder normal-card" data-card-type="live" data-card-id="${room_id}" href="//live.bilibili.com/${room_id}?jumpfrom=27012" target="_blank">
                <div class="flex pointer-events-none live-card-ctnr">
                    <div class="cover-box">
                        <i class="card-icon icon-cover default-cover"></i>
                        <div class="cover-img" style="background-image: url(${handleImageUrlToWebp(clearUrlHttp(cover!), 114 * devicePixelRatio)});"></div>
                        <div class="live-status ${living ? 'living' : 'live-end'}">${living ? '直播中' : '直播结束'}</div>
                    </div>
                    <div class="flex-1 min-w-0 flex flex-col justify-between live-cnt-ctnr">
                        <div class="live-title multiple-ellipsis ${option?.draw ? 'draw' : ''}" style="-webkit-box-orient: vertical;">${replaceHtmlToSafeStr(title!)}</div>
                        <div class="live-up truncate">
                            ${getSvgHtml('up')}
                        <span>${replaceHtmlToSafeStr(uname!)}</span>
                        </div>
                        <div class="flex items-center live-room-info">${!option?.draw && living ? `${changeNumberToWanYi(online!)}人气 丨 ${area_v2_name}` : area_v2_name}</div>
                    </div>
                </div>
            </a>
      `
    } else {

        o = ` <div class="read-error-card media mobile slim-border">
                  <p class="p-1"></p>
                    <p class="flex items-center justify-center p-2">
                      <i class="card-icon icon-warning mr-1"></i>
                      <span>直播加载失败</span>
                    </p>
                  <p class="p-3"></p>
                </div>`
    }
    r.className = 'card-container live-card'
    // 通过html2Canvas 生成图片后插入
    return drawCardToBase64(o, r)
}

export const getLiveDetail = (itemId: string): Promise<Record<string, LiveCardCreateValue['info']>> => {
    // 请求接口获取卡片信息
    return Promise.resolve({
        [itemId]: {
            area_v2_name: "手工绘画",
            cover: "http://192.168.2.219:9000/smart-park/upload/20250521/d698b94bd4db9eeadfdc8300651221ff.png",
            face: "https://i1.hdslb.com/bfs/face/72d11ba24462066ee4b4aa5f5162a19a74360bcf.jpg",
            live_status: 1,
            online: 386,
            pendent_ru: "",
            pendent_ru_color: "",
            pendent_ru_pic: "",
            role: 0,
            room_id: 22478506,
            title: "bilibili主播的直播间",
            uid: 108918496,
            uname: "小鸟游银兰不画铯图了"
        },
    })
}
